const db = require('../config/db');

// 获取所有用户
async function getAllUsers(req, res) {
  try {
    const [rows] = await db.execute('SELECT id, username, gender, phone, unit_name, manager_id FROM users');
    res.json(rows);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '获取用户数据失败' });
  }
}

// 根据ID获取用户
async function getUserById(req, res) {
  try {
    const { id } = req.params;
    const [rows] = await db.execute('SELECT id, username, gender, phone, unit_name, manager_id FROM users WHERE id = ?', [id]);
    if (rows.length === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    res.json(rows[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '获取用户数据失败' });
  }
}

// 用户登录验证
async function loginUser(req, res) {
  try {
    const { username, password } = req.body;
    const [rows] = await db.execute('SELECT id, username, gender, phone, unit_name, manager_id FROM users WHERE username = ? AND password = ?', [username, password]);
    if (rows.length === 0) {
      return res.status(401).json({ error: '用户名或密码错误' });
    }
    res.json({ message: '登录成功', user: rows[0] });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '登录验证失败' });
  }
}

// 创建新用户
async function createUser(req, res) {
  try {
    const { username, password, gender, phone, unit_name, manager_id } = req.body;
    const [result] = await db.execute(
      'INSERT INTO users (username, password, gender, phone, unit_name, manager_id) VALUES (?, ?, ?, ?, ?, ?)',
      [username, password, gender, phone, unit_name, manager_id]
    );
    res.status(201).json({ id: result.insertId, message: '用户创建成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '创建用户失败' });
  }
}

// 更新用户
async function updateUser(req, res) {
  try {
    const { id } = req.params;
    const { username, password, gender, phone, unit_name, manager_id } = req.body;
    const [result] = await db.execute(
      'UPDATE users SET username = ?, password = ?, gender = ?, phone = ?, unit_name = ?, manager_id = ? WHERE id = ?',
      [username, password, gender, phone, unit_name, manager_id, id]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    res.json({ message: '用户更新成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '更新用户失败' });
  }
}

// 删除用户
async function deleteUser(req, res) {
  try {
    const { id } = req.params;
    const [result] = await db.execute('DELETE FROM users WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ error: '用户不存在' });
    }
    res.json({ message: '用户删除成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: '删除用户失败' });
  }
}

module.exports = {
  getAllUsers,
  getUserById,
  loginUser,
  createUser,
  updateUser,
  deleteUser
};